package com.fwj.authorization.staff.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fwj.authorization.staff.entity.SysPermission;
import com.fwj.authorization.staff.entity.SysRole;
import com.fwj.authorization.staff.entity.SysUser;
import com.fwj.authorization.staff.entity.SysUserExpand;
import com.fwj.authorization.staff.mapper.SysUserMapper;
import com.fwj.authorization.staff.service.SysUserExpandService;
import com.fwj.authorization.staff.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户
 *
 * @author 樊温军
 * @date 2025/3/18 上午10:32
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserExpandService sysUserExpandService;

    @Override
    public IPage<SysUser> getPage(Page<SysUser> page, SysUser sysUser) {
        return baseMapper.getPage(page, sysUser);
    }

    @Override
    public List<SysPermission> getPermissionListByUsername(String username) {
        List<SysPermission> list = baseMapper.getPermissionListByUsername(username);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list;
    }

    @Override
    public List<SysRole> getRoleListByUsername(String username) {
        List<SysRole> list = baseMapper.getRoleListByUsername(username);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list;
    }

    @Override
    public SysUser getUserByUsername(String username) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("username", username);
        List<SysUser> list = baseMapper.selectByMap(queryMap);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public void updateLastLoginTime(String username) {
        sysUserExpandService.update(Wrappers.<SysUserExpand>lambdaUpdate()
                .set(SysUserExpand::getLastLoginTime, LocalDateTime.now())
                .eq(SysUserExpand::getUsername, username));
    }
}
